package com.xinxing.city.recovery.ui;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.xinxing.city.recovery.APPRuntime;
import com.xinxing.city.recovery.Constant;
import com.xinxing.city.recovery.DI;
import com.xinxing.city.recovery.DeviceKernel;
import com.xinxing.city.recovery.R;
import com.xinxing.city.recovery.Tools;
import com.xinxing.city.recovery.adapter.AreaSelAdapter;
import com.xinxing.city.recovery.databinding.ActivitySetBucketBinding;
import com.xinxing.city.recovery.entitys.AreaSelBean;
import com.xinxing.city.recovery.entitys.BucketType;

import com.xinxing.city.recovery.entitys.Catalogs;
import com.xinxing.city.recovery.entitys.HardwareCategory;
import com.xinxing.city.recovery.entitys.KernelAction;
import com.xinxing.city.recovery.entitys.KernelActions;

import com.xinxing.city.recovery.interfaces.ICallBackWeight;
import com.xinxing.city.recovery.interfaces.IDeviceKernel;
import com.xinxing.city.recovery.interfaces.ISerialSendReceiveData;
import com.xinxing.city.recovery.net.BaseTask;
import com.xinxing.city.recovery.net.RetroFactory;
import com.xinxing.city.recovery.utils.MyDialog;
import com.xinxing.city.recovery.utils.SharedPreferencesUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.reflect.Type;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SetBucketActivity extends AppCompatActivity {
    private ActivitySetBucketBinding binding;
    private List<HardwareCategory> hardType;
    private int bucketNum;
    private ProgressBar progressBar;
    private String cabinetCode;
    private String cabinetName;
    private List<BucketType> bucketTypes =new ArrayList<>();
    private BucketType bucketBeanInfo;
    private BucketType bucketBean;
    private Gson gson;
    private TextView tvRFID;
    private IDeviceKernel deviceKernel;
    private float fw = 0;
    private float sw = 0;
    private TextView tvPiWeight,fWeight,sWeight;
    private ISerialSendReceiveData serialSendReceiveData;
    private APPRuntime appRuntime;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this,R.layout.activity_set_bucket);
        bucketBean = new BucketType();
        deviceKernel = DI.getInstance(IDeviceKernel.class);
        serialSendReceiveData =  DI.getInstance(ISerialSendReceiveData.class);
        appRuntime = DI.getInstance(APPRuntime.class);
        gson = new Gson();
        //编号
        Intent intent = getIntent();
        bucketNum = intent.getIntExtra("bucketNum",1);
        cabinetCode = intent.getStringExtra("cabinetCode");
        cabinetName = intent.getStringExtra("cabinetName");
        binding.setCabinetCode(cabinetCode);
        binding.setCabinetName(cabinetName);
        progressBar = findViewById(R.id.progressBar);
        EventBus.getDefault().register(this);
        //权限检测
        checkRight();
        //初始化页面
        initPage();
        tvRFID = findViewById(R.id.tv_rfid);
        tvPiWeight = findViewById(R.id.pi_weight);
        fWeight = findViewById(R.id.f_weight);
        sWeight = findViewById(R.id.s_weight);
        Constant.PI_WEIGHT = true;
        findViewById(R.id.rfid_info).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Spinner spinner = findViewById(R.id.recycleCata);
                Object selItem = spinner.getSelectedItem();
                JsonElement jsonElement = gson.fromJson(gson.toJson(selItem), JsonElement.class);
                JsonObject resObeject = jsonElement.getAsJsonObject();
                if (resObeject.get("code").getAsString() == null || resObeject.get("code").getAsString().isEmpty()) {
                    Tools.logTips("请选择桶分类！", getSupportFragmentManager());
                    return;
                } else {
                    deviceKernel.getRfid().singleRfid();
                    mHandler.sendEmptyMessageDelayed(2, 1000);
                }
            }
        });
        findViewById(R.id.tv_f_weight).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        int num = 1;
                        if(binding.bucketName.getText().toString().contains("纸")){
                            num =1 ;
                        }else if(binding.bucketName.getText().toString().contains("金属")){
                            num =2 ;
                        }else if(binding.bucketName.getText().toString().contains("塑料")){
                            num =3 ;
                        }else if(binding.bucketName.getText().toString().contains("全品")){
                            num =4 ;
                        }
                        serialSendReceiveData.getWeight(num, new ICallBackWeight() {
                            @Override
                            public void setWeight(int num, long weight) {

                                Log.e("TTT", "f" + weight);
                                Message msg = new Message();
                                msg.what = 3;
                                msg.obj = String.valueOf(weight);
                                mHandler.sendMessage(msg);
//                                EventBus.getDefault().post(new KernelAction(KernelActions.FWEIGHTS, null));
                            }
                        });
                    }
                }).start();
            }
        });
        findViewById(R.id.tv_s_weight).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        int num = 1;
                        if(binding.bucketName.getText().toString().contains("纸")){
                            num =1 ;
                        }else if(binding.bucketName.getText().toString().contains("金属")){
                            num =2 ;
                        }else if(binding.bucketName.getText().toString().contains("塑料")){
                            num =3 ;
                        }else if(binding.bucketName.getText().toString().contains("全品")){
                            num =4 ;
                        }
                        serialSendReceiveData.getWeight(num, new ICallBackWeight() {
                            @Override
                            public void setWeight(int num, long weight) {

                                Log.e("TTT", "s" + weight);
                                Message msg = new Message();
                                msg.what = 4;
                                msg.obj = String.valueOf(weight);
                                mHandler.sendMessage(msg);
                            }
                        });
                    }
                }).start();
            }
        });
        findViewById(R.id.tv_pi_weight).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mHandler.sendEmptyMessage(5);
            }
        });
    }
    Handler mHandler = new Handler(Looper.myLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 2:
                    deviceKernel.getRfid().singleRfid();
                    mHandler.sendEmptyMessageDelayed(2, 1000);
                    break;
                case 3:
                    String s = (String) msg.obj;

                    fWeight.setText(s);
                    break;
                case 4:
                    String s2 = (String) msg.obj;
                    sWeight.setText(s2);

                    break;
                case 5:
                    String w1 = fWeight.getText().toString();
                    String w2 = sWeight.getText().toString();

                    if(!w1.equals("")&&!w2.equals("")) {
                        float we1 = Float.valueOf(w1)/1000;
                        float we2 = Float.valueOf(w2)/1000;

                        float we3 = we2 -we1;
                        long we4 = Long.valueOf(w2)-Long.valueOf(w1);
                        if(we3>0) {
                            DecimalFormat decimalFormat = new DecimalFormat("#0.00"); // 创建 DecimalFormat 对象并设置格式模式 "#0.00"
                            String formattedNumber = decimalFormat.format((float) (we2 - we1));
                            tvPiWeight.setText(String.valueOf(formattedNumber));

                            if(bucketBeanInfo!=null){
                                SharedPreferencesUtils.setParam(SetBucketActivity.this,"piWeight"+bucketBeanInfo.getNum(),String.valueOf(we4));
                                appRuntime.setPiWeight(bucketBeanInfo.getNum(),we4);
                            }

                        }
                    }
                    break;
            }
        }
    };


    private String getRfid() {
        Spinner spinner = findViewById(R.id.recycleCata);
        Object selItem = spinner.getSelectedItem();
        JsonElement jsonElement = gson.fromJson(gson.toJson(selItem), JsonElement.class);
        JsonObject resObeject = jsonElement.getAsJsonObject();
        String code;
        String idCodePrefix;
        if (resObeject.get("code").getAsString() == null || resObeject.get("code").getAsString().isEmpty()) {
            Tools.logTips("请选择桶分类！", getSupportFragmentManager());
            code = "";
            idCodePrefix="";
        } else {
            code = resObeject.get("code").getAsString();
            idCodePrefix = resObeject.get("idCodePrefix").getAsString();
        }
        String item ="";
        List<String> rfids = deviceKernel.getRuntime().getNowRfid();
        for (String rifd : rfids) {
            String rfidPrefix2 = rifd.substring(0,1);
            if(rfidPrefix2.equals(idCodePrefix)){
                item = rifd;
                mHandler.removeMessages(2);
                break;
            }
        }

        return item;
    }
    List<Catalogs> catalogsList;
    /**
     * 回收桶登记展开
     */
    public void initPage() {
        List<AreaSelBean> areaList = new ArrayList<>();
        String str = (String) SharedPreferencesUtils.getParam(this,"set_category","");

        if (!str.equals("")) {
            Type dev = new TypeToken<List<Catalogs>>() {}.getType();
            catalogsList = gson.fromJson(str, dev);
        }else{
            catalogsList = new ArrayList<>();
        }
        for (int i = 0; i < catalogsList.size(); i++) {
            Catalogs item = catalogsList.get(i);
            AreaSelBean sel = new AreaSelBean();
            sel.setCode(item.getCode());
            sel.setName(item.getName());
            areaList.add(sel);
        }
        AreaSelAdapter adapter = new AreaSelAdapter(this, android.R.layout.simple_spinner_item, areaList);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        binding.recycleCata.setAdapter(adapter);

        String bucketStr = (String) SharedPreferencesUtils.getParam(this, "bucket", "");

        if (!bucketStr.equals("")) {
            Type dev = new TypeToken<List<BucketType>>() {}.getType();
            bucketTypes = gson.fromJson(bucketStr, dev);
        }
        if(bucketTypes.size()>bucketNum-1) {
            bucketBeanInfo = bucketTypes.get(bucketNum - 1);
        }
        if(bucketBeanInfo!=null){
            if (bucketBeanInfo.getStatus().equals("01")) {
                binding.bucketStatusBtn2.setChecked(true);
            } else {
                binding.bucketStatusBtn1.setChecked(true);
            }
            if (bucketBeanInfo.getCompressStatus().equals("01")) {
                binding.bucketCompressStatusBtn2.setChecked(true);
            } else {
                binding.bucketCompressStatusBtn1.setChecked(true);
            }

            binding.bucketName.setText(bucketBeanInfo.getName());

            binding.bucketCapacity.setText(bucketBeanInfo.getCapacity());
            DecimalFormat decimalFormat = new DecimalFormat("#0.00"); // 创建 DecimalFormat 对象并设置格式模式 "#0.00"
            String formattedNumber = decimalFormat.format((float) (bucketBeanInfo.getWeight()));
            binding.bucketUsedCapacity.setText(formattedNumber);
            List<String> rfids = deviceKernel.getRuntime().getNowRfid();
            for (int i = 0;i < catalogsList.size();i++) {
                Catalogs item = catalogsList.get(i);

                Log.e(item.getCode(),bucketBeanInfo.getRecycleCataCode());
                if (bucketBeanInfo != null && item.getCode().equals(bucketBeanInfo.getRecycleCataCode())) {
                    binding.recycleCata.setSelection(i);
                    for (String rifd : rfids) {
                        String rfidPrefix2 = rifd.substring(0,1);
                        if(rfidPrefix2.equals(item.getIdCodePrefix())){
                            binding.tvRfid.setText(rifd);
                            break;
                        }
                    }

                }
            }
        }
        //加载分类信息
        getHardType();
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onKernelEvent(KernelAction kernelAction) {
        int actionType = kernelAction.getActionType();
        List<String> params = kernelAction.getActionParams();
        switch (actionType) {
            case KernelActions.RFID_READ:
                tvRFID.setText(getRfid());
                break;
        }

    }

    /**
     * 条件判断
     */
    private void checkRight() {
        if (bucketNum == 0) {
            MyDialog myDialog = MyDialog.newInstance("提示","未找到当前桶编号!","返回","");
            myDialog.setMyDialogListener(new MyDialog.MyDialogListener() {
                @Override
                public void onPositiveClick() {
                    finish();
                }
                @Override
                public void onNegativeClick() {

                }
            });
            myDialog.show(getSupportFragmentManager(),"MyDialog");
        }
    }
    /**
     * 回收桶登记提交
     */
    public void  bucketSub(View view){
        Map<String, String> par = new HashMap<>();

        EditText ename = findViewById(R.id.bucket_name);
        if (binding.bucketName.getText().toString() == null || ename.getText().toString().isEmpty() ) {
            Tools.logTips("桶名不能为空！",getSupportFragmentManager());
            return ;
        }

        par.put("name", binding.bucketName.getText().toString());
        bucketBean.setName(par.get("name"));

        RadioGroup radioGroup = findViewById(R.id.bucket_onlineStatus);
        int selectedRadioButtonId = radioGroup.getCheckedRadioButtonId();
        String onlineStatus = "00";
        if (selectedRadioButtonId != -1) {
            RadioButton selectedRadioButton = findViewById(selectedRadioButtonId);
            String selectedValue = selectedRadioButton.getText().toString();
            if (!selectedValue.equals("开启")) {
                onlineStatus = "01";
            }
        }
        par.put("onlineStatus", onlineStatus);
        bucketBean.setStatus(onlineStatus);


        par.put("cabinetName", cabinetName);
        par.put("cabinetCode", cabinetCode);
        par.put("deviceSerialNum", DeviceKernel.deviceSerialNum);
        bucketBean.setCabinetCode(cabinetCode);
        bucketBean.setCabinetName(cabinetName);


        RadioGroup radioGroup2 = findViewById(R.id.bucket_compressStatus);
        int selectedRadioButtonId2 = radioGroup2.getCheckedRadioButtonId();
        String compressStatus = "00";
        if (selectedRadioButtonId2 != -1) {
            RadioButton selectedRadioButton = findViewById(selectedRadioButtonId2);
            String selectedValue = selectedRadioButton.getText().toString();
            if (!selectedValue.equals( "空闲")) {
                compressStatus = "01";
            }
        }
        par.put("compressStatus", compressStatus);
        bucketBean.setCompressStatus(compressStatus);

        EditText capacity = findViewById(R.id.bucket_capacity);
        if (capacity.getText().toString() == null || capacity.getText().toString().isEmpty() ) {
            Tools.logTips("容量不能为空！",getSupportFragmentManager());
            return ;
        }
        par.put("capacity", capacity.getText().toString());
        bucketBean.setCapacity(capacity.getText().toString());

        EditText usedCapacity = findViewById(R.id.bucket_usedCapacity);
        if (usedCapacity.getText().toString() == null || usedCapacity.getText().toString().isEmpty() ) {
            Tools.logTips("使用容量不能为空！",getSupportFragmentManager());
            return ;
        }
        par.put("usedCapacity", usedCapacity.getText().toString());
        bucketBean.setUsedCapacity(usedCapacity.getText().toString());



        Spinner spinner = findViewById(R.id.recycleCata);
        Object selItem = spinner.getSelectedItem();
        JsonElement jsonElement = gson.fromJson(gson.toJson(selItem), JsonElement.class);
        JsonObject resObeject = jsonElement.getAsJsonObject();
        if (resObeject.get("code").getAsString() == null || resObeject.get("code").getAsString().isEmpty() ) {
            Tools.logTips("请选择桶分类！",getSupportFragmentManager());
            return ;
        }
        par.put("recycleCataCode",resObeject.get("code").getAsString());
        par.put("recycleCataName",resObeject.get("name").getAsString());
        bucketBean.setRecycleCataCode(resObeject.get("code").getAsString());
        bucketBean.setRecycleCataName(resObeject.get("name").getAsString());

        HardwareCategory itype =  hardType.get(1);
        par.put("hardwareName", itype.getName());
        par.put("hardwareLevel", itype.getLevel());
        par.put("hardwareCode", itype.getCode());
        bucketBean.setHardwareCode(itype.getCode());
        bucketBean.setHardwareName(itype.getName());
        bucketBean.setHardwareLevel(itype.getLevel());

        setBucketAdd(par);
    }
    /**
     * 加载分类信息
     */
    private void getHardType() {

        progressBar.setVisibility(View.VISIBLE); // 显示加载动画
        new BaseTask<List<HardwareCategory>>(this, RetroFactory.getJsonService().getHardware()).handleResponse(new BaseTask.ResponseListener<List<HardwareCategory>>() {
            @Override
            public void onSuccess(List<HardwareCategory> hardwareCategories) {
                hideLoadding(progressBar);
                hardType = hardwareCategories;
            }

            @Override
            public void onFail() {
                hideLoadding(progressBar);
            }
        });
    }
    /**
     * 添加注册桶
     */
    private void setBucketAdd(Map<String, String> par) {
        progressBar.setVisibility(View.VISIBLE);
        if(bucketBeanInfo==null){
            new BaseTask<String>(this,RetroFactory.getJsonService().addBucket(RetroFactory.getJSON2(par))).handleResponse(new BaseTask.ResponseListener<String>() {
                @Override
                public void onSuccess(String o) {
                    progressBar.setVisibility(View.GONE);
                    updata(par,o);
                }

                @Override
                public void onFail() {
                    progressBar.setVisibility(View.GONE);
                }
            });
        }else{
            par.put("code", bucketBeanInfo.getCode());

            new BaseTask<>(this,RetroFactory.getJsonService().updataBucket(RetroFactory.getJSON2(par))).handleResponse(new BaseTask.ResponseListener() {
                @Override
                public void onSuccess(Object o) {
                    progressBar.setVisibility(View.GONE);
                    updata(par,null);
                }

                @Override
                public void onFail() {
                    progressBar.setVisibility(View.GONE);
                }
            });
        }
    }
    /**
     * 隐藏loadding
     */
    public void hideLoadding(ProgressBar progressBar) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                progressBar.setVisibility(View.GONE);
            }
        });
    }
    private void updata(Map<String, String> par,String code){
        if(bucketBeanInfo==null){
            bucketBeanInfo = new BucketType();
        }
        bucketBeanInfo.setStatus(par.get("onlineStatus"));
        bucketBeanInfo.setCompressStatus(par.get("compressStatus"));
        bucketBeanInfo.setHardwareName(par.get("hardwareName"));
        bucketBeanInfo.setCapacity(par.get("capacity"));
        bucketBeanInfo.setHardwareLevel(par.get("hardwareLevel"));
        bucketBeanInfo.setHardwareCode(par.get("hardwareCode"));
        bucketBeanInfo.setName(par.get("name"));
        bucketBeanInfo.setRecycleCataName(par.get("recycleCataName"));
        bucketBeanInfo.setUsedCapacity(par.get("usedCapacity"));
        bucketBeanInfo.setRecycleCataCode(par.get("recycleCataCode"));
        bucketBeanInfo.setCabinetName(par.get("cabinetName"));
        bucketBeanInfo.setCabinetCode(par.get("cabinetCode"));
        if(par.get("recycleCataName").equals("纸类")){
            bucketBeanInfo.setNum(1);
        }else if(par.get("recycleCataName").equals("金属类")){
            bucketBeanInfo.setNum(2);
        }
        else if(par.get("recycleCataName").equals("塑料类")){
            bucketBeanInfo.setNum(3);
        }
        else if(par.get("recycleCataName").equals("全品类")){
            bucketBeanInfo.setNum(4);
        }
        if(code!=null)
             bucketBeanInfo.setCode(code);
        if(bucketTypes.size()>=bucketNum) {
            bucketTypes.set(bucketNum - 1, bucketBeanInfo);
        }else{
            bucketTypes.add(bucketBeanInfo);
        }
        Log.e("TTTT","____>>>>>:  "+gson.toJson(bucketTypes));

        SharedPreferencesUtils.setParam(SetBucketActivity.this,"bucket",gson.toJson(bucketTypes));
        MyDialog myDialog = MyDialog.newInstance("提示","设置成功！返回设备管理！","确定","取消");
        myDialog.setMyDialogListener(new MyDialog.MyDialogListener() {
            @Override
            public void onPositiveClick() {
                finish();
            }
            @Override
            public void onNegativeClick() {
                myDialog.dismiss();
            }
        });
        myDialog.show(getSupportFragmentManager(),"MyDialog");
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
